//
//  TYZBaseViewController.m
//  DriveSchoolCoach
//
//  Created by TangBin on 2019/7/4.
//  Copyright © 2019 TangBin. All rights reserved.
//

#import "TYZBaseViewController.h"


@interface TYZBaseViewController ()
{
    CGFloat ignoredScrollViewContentInsetTop_;
}
/**
 是否第一次，进入界面就显示下拉，默认是NO
 */
@property (nonatomic, assign) BOOL isFirstRefresh;

@property (nonatomic, strong) UIButton *btnBack;

/**
 UIApplicationDidChangeStatusBarFrameNotification
 
 @param notification note
 */
- (void)layoutControllerSubViews:(NSNotification *)notification;

/**
 UIApplicationWillChangeStatusBarFrameNotification
 
 @param notification note
 */
- (void)statusBarFrameWillChange:(NSNotification *)notification;

/**
 iPhone/iOS开启个人热点的相关位置调整
 */
- (void)layoutControllerSubViews;


- (void)initWithCustNavView;

@end

@implementation TYZBaseViewController

- (void)dealloc
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
#if !__has_feature(objc_arc)
    [_popResultBlock release], _popResultBlock = nil;
    [super dealloc];
#endif
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        
    }
    return self;
}

- (void)viewDidLoad
{
    //    NSLog(@"%s", __func__);
    [super viewDidLoad];
    
    // 及时刷新当前控制器，手动调用方法
    [UIViewController attemptRotationToDeviceOrientation];
    
    if (@available(iOS 11.0, *))
    {
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
    else
    {
        // Do any additional setup after loading the view, typically from a nib.
        if ([self respondsToSelector:@selector(setAutomaticallyAdjustsScrollViewInsets:)])
        {
            // 简单点说就是automaticallyAdjustsScrollViewInsets根据按所在界面的status bar，navigationbar，与tabbar的高度，自动调整scrollview的 inset,设置为no，不让viewController调整，我们自己修改布局即可~
            
            // setAutomaticallyAdjustsScrollViewInsets ios11之后不起作用了
            [self setAutomaticallyAdjustsScrollViewInsets:NO];
        }
    }
    
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
    {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
    }
    
    self.view.backgroundColor = kMainBaseViewBackgroundColor;//[UIColor colorWithHexString:@"#f7f9fc"];//[UIColor colorWithRed:242.0f/255 green:244.0f/255 blue:245.0f/255 alpha:1];
    
    //    self.navigationController.navigationBar.translucent = NO;
    //    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    
    [self initWithVar];
    
    
    [self initWithNavBar];
    
    [self initWithSubView];
    
    // 绑定viewmodel
    [self bindViewModel];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self layoutControllerSubViews];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//- (UIStatusBarStyle)preferredStatusBarStyle {
//    return UIStatusBarStyleLightContent;
//}


/**
 *  初始化变量
 */
- (void)initWithVar
{
    //    NSLog(@"%s", __func__);
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameWillChange:) name:UIApplicationWillChangeStatusBarFrameNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(layoutControllerSubViews:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
    
    [self initWithViewModel];
}

/**
 *  初始化navbar视图
 */
- (void)initWithNavBar
{
    //    NSLog(@"%s", __func__);
    [self initWithCustNavView];
    
}

- (void)initWithCustNavView
{
    CGRect frame = CGRectMake(0, 0, kScreenWidth, NAVBAR_HEIGHT_STATUS);
    _custNavView = [[ZHNavView alloc] initWithFrame:frame];
}

/**
 *  初始化子视图
 */
- (void)initWithSubView
{
    
    [self.view addSubview:self.noDataView];
}

- (void)initWithRootContent:(BOOL)isRefresh
{
    CGRect frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - NAVBAR_HEIGHT_STATUS);
    _rootContent = [[UIScrollView alloc] initWithFrame:frame];
    _rootContent.backgroundColor = [UIColor whiteColor];
    _rootContent.showsVerticalScrollIndicator = NO;
    _rootContent.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_rootContent];
    
    if (!isRefresh) {
        return;
    }
    
    // 1. 下拉刷新(进入刷新状态就会调用doRefreshData)
    // dataKey 用于存储刷新事件，可以保证不同的界面拥有不同的刷新时间
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(doRefreshData)];
//    EDSCarStartHeader *header = [EDSCarStartHeader headerWithRefreshingTarget:self refreshingAction:@selector(doRefreshData)];
//    header.lastUpdatedTimeLabel.hidden = YES;
//    header.stateLabel.hidden = YES;
    header.ignoredScrollViewContentInsetTop = ignoredScrollViewContentInsetTop_;
    [header setTitle:@"下拉刷新" forState:MJRefreshStateIdle];
    [header setTitle:@"松开刷新" forState:MJRefreshStatePulling];
    [header setTitle:@"正在刷新中" forState:MJRefreshStateRefreshing];
    //    header.stateLabel.font
    //    header.lastUpdatedTimeLabel.font
    //    header.stateLabel.textColor
    self.rootContent.mj_header = header;
    
    if (_isFirstRefresh)
    {
        [self.rootContent.mj_header beginRefreshing];
    }
    
    [self hiddenHeaderView:YES];
}

/**
 初始化viewmodel
 */
- (void)initWithViewModel
{
    
}

/**
 绑定viewmodel
 */
- (void)bindViewModel
{
    
}

/**
 *  初始化返回按钮
 */
- (void)initWithBackButton
{
    if (!_btnBack)
    {
        // [_leftBarButton setImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        UIImage *image = [UIImage imageNamed:@"ic-nav-black-back"];
        image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
        //        btnBack.frame = CGRectMake(0, 0, image.size.width, image.size.height);
        btnBack.frame = CGRectMake(0, 0, 30, 44);
        [btnBack setImage:image forState:UIControlStateNormal];
        [btnBack addTarget:self action:@selector(clickedBack:) forControlEvents:UIControlEventTouchUpInside];
//        btnBack.backgroundColor = [UIColor purpleColor];
//        btnBack.imageEdgeInsets = UIEdgeInsetsMake(0, -18, 0, 0);
        self.btnBack = btnBack;
//        self.btnBack.backgroundColor = [UIColor redColor];
    }
    UIBarButtonItem *itemBack = [[UIBarButtonItem alloc] initWithCustomView:_btnBack];
    self.navigationItem.leftBarButtonItem = itemBack;
    
}


#pragma mark - 当有下来刷新的时候使用

/// 初始化
/// @param firstShowRefresh 第一次进入页面的时候，是否显示下拉刷新
- (instancetype)initWithFirstShowRefresh:(BOOL)firstShowRefresh
{
    if (self = [super init])
    {
        _isFirstRefresh = firstShowRefresh;
    }
    return self;
}

- (void)setIgnoredScrollViewContentInsetTop:(CGFloat)ignoredScrollViewContentInsetTop
{
    if (!self.rootContent)
    {
        return;
    }
    ignoredScrollViewContentInsetTop_ = ignoredScrollViewContentInsetTop;
    self.rootContent.mj_header.ignoredScrollViewContentInsetTop = ignoredScrollViewContentInsetTop;
}


- (void)beginRefreshing
{
    if (!self.rootContent)
    {
        return;
    }
    [self.rootContent.mj_header beginRefreshing];
}

/**
 下拉刷新数据
 */
- (void)doRefreshData
{
    _isAllFinished = NO;
    self.isHeadRefresh = YES;
}

- (BOOL)isHeaderRefreshing
{
    if (!self.rootContent)
    {
        return NO;
    }
    return self.rootContent.mj_header.isRefreshing;
}

/**
 结束所有刷新
 */
- (void)endAllRefreshing
{
    [self endHeaderRefreshing];
}

/**
 下拉刷新结束
 */
- (void)endHeaderRefreshing
{
    if (!self.rootContent)
    {
        return;
    }
    [self.rootContent.mj_header endRefreshing];
}

/**
 隐藏header
 
 @param hidden hidden description
 */
- (void)hiddenHeaderView:(BOOL)hidden
{
    if (!self.rootContent)
    {
        return;
    }
    [self.rootContent.mj_header setHidden:hidden];
}






#pragma mark - setter getter
- (TYZNoDataOrErrorView *)noDataView
{
    if (!_noDataView)
    {
        int width = kScreenWidth - 60;
        CGRect frame = CGRectMake(30, (kScreenHeight - width) * 0.5 - NAVBAR_HEIGHT_STATUS - 50, width, width);
        _noDataView = [[TYZNoDataOrErrorView alloc] initWithFrame:frame];
        _noDataView.hidden = YES;
    }
    return _noDataView;
}

/**
 隐藏或者显示没有数据的视图
 
 @param hidden hidden description
 */
- (void)noDataViewHidden:(BOOL)hidden
{
    self.noDataView.hidden = hidden;
    if (!hidden)
    {
        [self.view bringSubviewToFront:self.noDataView];
    }
}

- (void)updateWithBackImage:(NSString *)imageName
{
    UIImage *image = [UIImage imageNamed:imageName];
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [_btnBack setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
}

/**
 *  从服务端请求数据
 */
- (void)fromServerRequestData
{
    
}

/**
 *  返回按钮函数
 *
 *  @param sender 传进来的参数
 */
- (void)clickedBack:(id)sender
{
    if (self.presentingViewController)
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}


/**
 UIApplicationDidChangeStatusBarFrameNotification
 
 @param notification note
 */
- (void)layoutControllerSubViews:(NSNotification *)notification
{
    [self layoutControllerSubViews];
}

/**
 UIApplicationWillChangeStatusBarFrameNotification
 
 @param notification note
 */
- (void)statusBarFrameWillChange:(NSNotification *)notification
{
    [self layoutControllerSubViews];
}

/**
 UIApplicationDidChangeStatusBarFrameNotification
 */
- (void)layoutControllerSubViews
{
    BOOL isHotSpot = NO;
    if (IS_HOTSPOT_CONNECTED)
    {
        isHotSpot = YES;
    }
    [self layoutControllerSubViewsHotSpot:isHotSpot];
    
    
    /*
     CGRect statusBarRect = [[UIApplication sharedApplication] statusBarFrame];
     if (statusBarRect.size.height == 40)
     {
     [mytable setFrame:CGRectMake(0, -20, 320, UI_View_Hieght+64-58)];
     [bottomView setFrame:CGRectMake(0,UI_View_Hieght+64-58-20,320, 58)];
     }
     else
     {
     [mytable setFrame:CGRectMake(0, 0, 320, UI_View_Hieght+64-58)];
     [bottomView setFrame:CGRectMake(0,UI_View_Hieght+64-58,320, 58)];
     }
     */
    
}

- (void)layoutControllerSubViewsHotSpot:(BOOL)isHotSpot
{
    //    NSLog(@"%s", __func__);
    //    printf("%s\n", __func__);
}

@end

